package com.jike.noobmoney.mvp.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.TaskDetailSubmitAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BaseEntity;
import com.jike.noobmoney.entity.SubmitOrderDetailEntity;
import com.jike.noobmoney.mvp.view.widget.BuHeGeDialog;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.AppUtils;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SheshuSubmitTaskActivity extends BaseActivity {


    public static final String o_id = "o_id";
    public static final String o_title = "o_title";
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.ll_img)
    LinearLayout llImg;
    @BindView(R.id.avi)
    AVLoadingIndicatorView avi;
    @BindView(R.id.tv_submit_title)
    TextView tvSubmitTitle;
    @BindView(R.id.tv_jine)
    TextView tvJine;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    private String orderId;
    private String userid;
    private Call<SubmitOrderDetailEntity> submitOrderDetailEntityCall;
    private String title;


    @BindView(R.id.tv_task_id)
    TextView tv_task_id;

    @BindView(R.id.tv_task_title)
    TextView tv_task_title;

    @BindView(R.id.tv_tijiaotime)
    TextView tv_tijiaotime;

    @BindView(R.id.tv_tijiao)
    TextView tv_tijiao;

    @BindView(R.id.tv_user_id)
    TextView tv_user_id;
    @BindView(R.id.tv_u_id)
    TextView tv_u_id;

    @BindView(R.id.ll_isshow)
    LinearLayout ll_isshow;
    @BindView(R.id.tv_info)
    TextView tv_info;

    @BindView(R.id.tv_text)
    TextView tv_text;

    @BindView(R.id.tv_finish_percent)
    TextView tv_finish_percent;


    @BindView(R.id.tv_type_title)
    TextView tvTypeTitle;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_ecode)
    ImageView ivEcode;
    @BindView(R.id.tv_http)
    TextView tvHttp;

    @BindView(R.id.tv_sx)
    Button tv_sx;

    private TaskDetailSubmitAdapter taskSubmitAdapter;
    private List<SubmitOrderDetailEntity.OrderinfoBean.TaskstepBean> mData = new ArrayList<>();
    private Call<BaseEntity> cancleOrder;

    @Override
    protected int layoutResID() {
        return R.layout.activity_submit_task_update_ss;
    }

    @Override
    protected void initData() {
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra(SheshuSubmitTaskActivity.o_id);
            title = getIntent().getStringExtra(SheshuSubmitTaskActivity.o_title);
        }
        tvTitle.setText(title);
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        taskSubmitAdapter = new TaskDetailSubmitAdapter(this);
        recyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerview.setAdapter(taskSubmitAdapter);
        recyclerview.setNestedScrollingEnabled(false);
        getData();
    }

    /**
     * 获取数据
     */
    private void getData() {
        avi.show();
        submitOrderDetailEntityCall = RetrofitHelper.getInstance().submitOrderDetail(orderId);
        submitOrderDetailEntityCall.enqueue(new Callback<SubmitOrderDetailEntity>() {
            @Override
            public void onResponse(Call<SubmitOrderDetailEntity> call, Response<SubmitOrderDetailEntity> response) {
                if (response != null) {
                    SubmitOrderDetailEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            initView(body);
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }

                    }
                    if (avi != null) {
                        avi.hide();
                    }
                }
            }

            @Override
            public void onFailure(Call<SubmitOrderDetailEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
                if (avi != null) {
                    avi.hide();
                }
            }
        });

    }
    /**
     * 如果要全屏,重写这个方法返回false
     */
    public Boolean isfits() {
        return true;
    }

    /**
     * 如果要白色主题,重写这个方法返回false
     */
    public boolean ismain() {
        return true;
    }
    /**
     * 加载视图
     */
    private void initView(SubmitOrderDetailEntity body) {
        SubmitOrderDetailEntity.OrderinfoBean orderinfo = body.getOrderinfo();
        if (orderinfo != null) {
            tvSubmitTitle.setText(TextUtils.isEmpty(orderinfo.getTaskname()) ? "小白任务" : orderinfo.getTaskname());
            int status = orderinfo.getStatus();
            tvStatus.setText(status == 3 ? "审核中" : "已审核");
            tvMoney.setText("+" + orderinfo.getMoney() + "豆");
            tvJine.setText("任务金额");
            tv_text.setText(orderinfo.tasktext);

            tv_task_id.setText("任务ID:"+orderinfo.getT_id());

            tv_task_title.setText("任务名称："+orderinfo.getTaskname());

            tv_tijiaotime.setText("接单时间："+orderinfo.getCreatetime());

            tv_tijiao.setText("提交时间："+orderinfo.getSubmittime());


            tv_user_id.setText("接单人："+orderinfo.getU_id());

            tv_u_id.setText("用户ID:"+orderinfo.getU_id());

            tv_finish_percent.setText("历史任务通过率:"+ ComUtils.getPercent(orderinfo.finishpercent));
            String flag=orderinfo.isinfo;
            if(flag.equals("0"))
            {
                ll_isshow.setVisibility(View.GONE);
            }else
            {
                ll_isshow.setVisibility(View.VISIBLE);
                tv_info.setText(orderinfo.getInfo());

            }
//            List<SubmitOrderDetailEntity.OrderinfoBean.SubmitpicBean> submitpic = orderinfo.getSubmitpic();
//            if (submitpic != null && submitpic.size() > 0) {
//                for (int i = 0; i < submitpic.size(); i++) {
//                    SubmitOrderDetailEntity.OrderinfoBean.SubmitpicBean submitpicBean = submitpic.get(i);
//                    String picture = submitpicBean.getPicture();
//
//                    if (TextUtils.isEmpty(picture)) {
//                        return;
//                    } else {
//                        ImageView imageView = new ImageView(this);
//                        Glide.with(context).load(ConstantValue.IMG_URL + picture).into(imageView);
//                        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//                        //param.leftMargin = 40;
//                        param.gravity = Gravity.CENTER;
//                        imageView.setLayoutParams(param);
//                        llImg.addView(imageView);
//                    }
//                }
//            } else {
//                TextView textView = new TextView(this);
//                textView.setText("暂无截图");
//                textView.setTextColor(getResources().getColor(R.color.c_4a4a4a));
//                llImg.addView(textView);
//            }

            int opentype = orderinfo.getOpentype(); //1二维码  2链接
            String openurl = orderinfo.getOpenurl();
            if (opentype == 1) {
                tvType.setText("二维码");
                ivEcode.setVisibility(View.VISIBLE);
                tvHttp.setVisibility(View.GONE);
                Glide.with(this).load(ConstantValue.IMG_BASEURL_QR_CODE + openurl).into(ivEcode);
            } else if (opentype == 2) {
                tvType.setText("链接");
                ivEcode.setVisibility(View.GONE);
                tvHttp.setVisibility(View.VISIBLE);
                tvHttp.setText(openurl);
            } else {
                tvTypeTitle.setVisibility(View.GONE);
                tvType.setVisibility(View.GONE);
                ivEcode.setVisibility(View.GONE);
                tvHttp.setVisibility(View.GONE);
            }

            ivEcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ArrayList<String> photoPaths = new ArrayList<>();
                    photoPaths.add(ConstantValue.IMG_BASEURL_QR_CODE + openurl);
                    PhotoPreview.builder()
                            .setPhotos(photoPaths)
                            .setCurrentItem(0)
                            .setShowDeleteButton(true)
                            .start((Activity) context);
                }
            });


            List<SubmitOrderDetailEntity.OrderinfoBean.TaskstepBean> taskstep = orderinfo.getTaskstep();
            if (taskstep != null) {
                mData.clear();
                mData.addAll(taskstep);
            }
            taskSubmitAdapter.refresh(mData);


        }

    }

    @OnClick({R.id.iv_back,R.id.tv_sx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sx:
                if (AppUtils.isFastClick()) {
                    ToastUtils.showShortToastSafe("操作有点频繁,稍后重试");
                    return;
                }
                BuHeGeDialog jiaPiaoDialog1 = BuHeGeDialog.getInstance();
                jiaPiaoDialog1.show(getSupportFragmentManager(), "buhege1");
                jiaPiaoDialog1.setClickCallback(number -> {
                    //确认
                    jiaPiaoDialog1.dismiss();
                    setAppealOrder(number);
                });
                break;
        }
    }


    /**
     用户投诉发布者（所谓的申述）
     */
    public void setAppealOrder(String text) {
        showProgress();
        cancleOrder = RetrofitHelper.getInstance().setAppeal(userid, orderId,text);
        cancleOrder.enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response != null) {
                    BaseEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                            setResult(200);
                            finish();
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                    dismissProgress();

                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
                dismissProgress();
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (submitOrderDetailEntityCall != null) {
            submitOrderDetailEntityCall.cancel();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
